<template>
  <div class="app-container">
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="公司名称">
          <el-input v-model="queryParams.name"  clearable />
        </el-form-item>
        <el-form-item label="热线电话">
          <el-input v-model="queryParams.phone"  clearable />
        </el-form-item>
        <el-form-item label="维修点城市" >
            <el-cascader
                v-model="selectedRegion"
                placeholder="请选择省/市"
                maxlength="30"
                clearable
                :options="proCityList"
                :props="props"
                @change="handleChange"
            />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="queryParams.type"
              placeholder="状态"
              clearable
          >
            <el-option label="封停" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-row>

    <el-row :gutter="5"> <!-- gutter 设为10，控制列之间的间距 -->
      <!-- 新增按钮 -->
      <el-col :span="3" style="padding: 0 2px;">
        <el-button type="success" :icon="Plus" plain @click="addPage"
                   style="padding: 6px 12px;">新增维修点</el-button>
      </el-col>

      <!-- 删除按钮 -->
      <el-col :span="2" style="padding: 0 2px;">
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow"
                   style="padding: 6px 12px;">删除</el-button>
      </el-col>

      <!-- 导入按钮 -->
      <el-col :span="1" style="padding: 0 2px;">
        <el-upload action="http://127.0.0.1:9090/mag/import/excel" :auto-upload="true"
                   :on-success="uploadSuccess">
          <template #trigger>
            <el-button type="warning" :icon="Download" plain style="padding: 6px 12px;">导入</el-button>
          </template>
        </el-upload>
      </el-col>
    </el-row>

    <el-row >
      <el-table
          :data="userList"
          border
          stripe
          style="height: 545px"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
            prop="id"
            label="ID"
            width="80"
        />
        <el-table-column
            prop="repName"
            label="公司名称"
            width="280"
        />
        <el-table-column
            prop="repAddress"
            label="详细地址"
            width="380"
        />
        <el-table-column
            prop="repNumber"
            label="热线电话"
        />
        <el-table-column
            label="状态"
        >
          <template #default="scope">
            <!--status必须是String类型,否则switch组件不识别-->
            <el-switch
                :model-value="String(scope.row.status)"
                inline-prompt
                active-value="1"
                active-text="正常"
                inactive-value="0"
                inactive-text="停用"
                class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="switchHandler(scope.row)"
            />
          </template>

        </el-table-column>

        <el-table-column label="操作" default="scope">
          <template #default="scope">

            <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="deleteOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="24">

        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>
  </div>
  <!-- 添加用户信息 -->
  <el-dialog v-model="editFormVisible" :title="editTitle" width="600px" append-to-body>
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef"  label-width="80px" >
      <el-row>
          <el-form-item label="区域名称" >
            <el-cascader
                v-model="selectedReg"
                placeholder="请选择省/市"
                maxlength="30"
                clearable
                :options="proCityList"
                :props="props"
                @change="onChange"
                style="width: 300px"
            />
          </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="公司名称" prop="repName">
          <el-input v-model="editForm.repName" placeholder="请输入公司名称" maxlength="30"
                    style="width: 300px"/>
        </el-form-item>
      </el-row>
      <el-row>
          <el-form-item label="详细地址" prop="repAddress">
            <el-input v-model="editForm.repAddress" placeholder="请输入详细地址" maxlength="30"
                      style="width: 300px"/>
          </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="热线电话" prop="repNumber">
          <el-input v-model="editForm.repNumber" placeholder="请输入热线电话" maxlength="30"
                    style="width: 300px"/>
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
  Download,
} from '@element-plus/icons-vue'
import {ref,onMounted,computed} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox} from "element-plus";
import loginUser from "@/stores/LoginUser.js";
let searchTime = ref(["",""])
let queryParams =ref({})
let userList = ref([])
let isSelectRow = ref(false)
let isAdd= ref(false);
const tableRef = ref(null);
const selectedRows = ref([]);
let proCityList = ref([])
let selectedRegion = ref([])
let selectedReg = ref([])
let resetQueryForm=()=>{
  queryParams.value = {
    pageNum:1,
    pageSize:10,
    name:'',
    phone:'',
    status:'',
    total:'',
  }
  // 重置级联选择器
  selectedRegion.value = []
}

const props = {
  value: 'repLabel', // 指定选项中作为“值”的字段（如后端返回的地区ID）
  label: 'repVal', // 指定选项中作为“显示文本”的字段（如地区名称）
  children: 'childRep', // 指定选项中作为“子选项列表”的字段（如后端返回的子地区列表字段）
  expandTrigger: 'hover',//鼠标悬浮时显示子数据
};

let uploadSuccess = ()=>{
  query()
}

let query = ()=>{
  // if (searchTime.value[0]!==''){
  //   queryParams.value.beginTime = formatDay(searchTime.value[0])
  //   queryParams.value.endTime = formatDay(searchTime.value[1])
  // }
  api.get('/repair/query',queryParams.value).then(res=>{
    console.log( res)
    userList.value = res.data.list
    queryParams.value.total = res.data.total
  })

}

// 添加级联选择器变化的处理方法
const handleChange = (value) => {
  if (value && value.length) {
    queryParams.value.pro = value[0]; // 省份值
    queryParams.value.city = value[1] || ''; // 城市值，可能不存在
  } else {
    queryParams.value.pro = '';
    queryParams.value.city = '';
  }
};

// // 添加级联选择器变化的处理方法
// const onChange = (value) => {
//   if (value && value.length) {
//     editForm.value.repPro = value[0]; // 省份值
//     editForm.value.repCity = value[1] || ''; // 城市值，可能不存在
//   } else {
//     editForm.value.repPro = '';
//     editForm.value.repCity = '';
//   }
// };

let switchHandler = (row)=>{
  ElMessageBox.confirm('是否修改用户['+row.id+']的状态？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (row.status == 1){
      row.status = '0'
    }else {
      row.status = '1'
    }
    console.log(row)
    api.post('/repair/save/update',row).then(res=>{
      ElMessage.success('修改成功')
      //query()
    })
  }).catch(() => {
    ElMessage.info('已取消修改');
  })

}
let editFormVisible = ref(false)
let editForm = ref({})
let editTitle = ref('编辑')
let addPage = ()=>{
  editFormVisible.value = true
  isAdd.value = true
  editTitle.value = "新增用户"
  reset()
}
let editFormRules = {
  repName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  repNumber: [
    { required: true, message: '请输入正确的手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, trigger: 'blur' }
  ],
  repAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],

}
let edit = (row)=>{
  console.log(row)

  editFormVisible.value = true
  isAdd.value = false
  editTitle.value = "编辑维修点"
  // editForm = ref(row)
  //因为editForm这个响应式遍历的值改变了，save方法中发请求用到了editForm的数据，故会调用自动save方法
  // 正确地更新响应式数据
  Object.assign(editForm.value, row)

  // 设置级联选择器的初始值
  if (row.repPro && row.repCity) {
    selectedReg.value = [row.repPro, row.repCity]
  } else {
    selectedReg.value = []
  }
}
/** 取消按钮 */
function cancel() {
  editFormVisible.value = false;
  reset();
}
function reset(){
  editForm.value ={
    id: '',
    repName: '',
    repAddress: '',
    repNumber: '',
    repPro: '',
    repCity: ''
  }
  // 重置级联选择器
  selectedReg.value = []
}
function save() {
  // 手动验证级联选择器
  if (!selectedReg.value || selectedReg.value.length === 0) {
    ElMessage.error('请选择所在城市')
    return
  }

  // 同步数据到 editForm
  editForm.value.repPro = selectedReg.value[0] || ''
  editForm.value.repCity = selectedReg.value[1] || ''

  api.post('/repair/save/update',editForm.value).then(res=>{
    if (res.code == 200){
      ElMessage.success("添加/修改成功")
      cancel()
      query()
    }else {
      ElMessage.error(res.msg)
    }

  })
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};
const deleteSelectedRows = () => {
  const idsArray = selectedRows.value.map(row => row.id);
  ElMessageBox.confirm('是否确认删除用户编号为['+idsArray+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    //ids变成,分割的字符串
    const ids = selectedRows.value.map(row => row.id).join(',');
    api.delete('/repair/delete/'+ids).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};
let deleteOne = (row)=>{
  ElMessageBox.confirm('是否确认删除用户编号为['+row.id+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
     api.delete('/repair/delete/'+row.id).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
 }

 function queryRroCityList(){
    api.get('/repair/pro/city').then(res=>{
      proCityList.value = res.data
    })
 }


onMounted(()=>{
  resetQueryForm();
  queryRroCityList();
  query();
})




</script>



<style scoped>


</style>